import config from '../../config/index'
import * as onemap from '../onemap'
import proj4 from 'proj4';
import { getColor,get2dColor } from '../gis2d/maputils'
import {useMapStoreStore} from '../../stores/index'
const store = useMapStoreStore()
// 引入proj4库用于坐标转换等相关操作（如果项目中还未引入）


export const add4490 = () => {

    var ellipsoid = Cesium.Ellipsoid.GRS80;
    var customProjection = new Cesium.GeographicProjection(ellipsoid);
    var extent = [73.62004852294922, 18.16888427734375, 134.76846313476562, 53.553741455078125];
    var rectangle = new Cesium.Rectangle.fromDegrees(extent[0], extent[1], extent[2], extent[3]);
    var customProjections = {};
    function registerProjection(projectionCode, projectionObject, extentRectangle) {
        customProjections[projectionCode] = {
            projection: projectionObject,
            extent: extentRectangle
        };
    }
    registerProjection('EPSG:4490', customProjection, rectangle);
}
// var customProjection =  add4490()
export let mimeMap = {};//添加删除映射
export let layerFlag = {};
export const loadWmsMap = (layerUrl, laycode, eqid, memo, version) => {
    // if (memo && laycode == "kspgyxcm") {
    //     loadEarthQuakeYXC(eqid, laycode, version)
    //     return
    // }
    if (mimeMap[laycode]) {
        mimeMap[laycode].show = true;
        layerFlag[laycode] = true;
        return
    }


var layers = "0.0"
    const parameters = {
        transparent: true,
        service: 'WMS',
        version: '1.3.0',
        //  CRS:"EPSG:4490",
        request: 'GetMap',
        format: 'image/png',
        // crs: 'EPSG:4326' // 指定SRS为EPSG:4326
        // 'CRS': '4490', 
        // 'VERSION': '1.3.0'
    }
    const tsparameters = {
        FORMAT: 'image/png',
        transparent: true,
        version: '1.3.0',
        //  bbox: '73.62004852294922, 18.16888427734375, 134.76846313476562, 53.553741455078125',
        layerDefs: JSON.stringify({
            ['0.0']: `earth_quake_id ='${eqid}' AND version='${version}' ` //10022
        })
    }
    if(laycode == "zxzzzj"  ){
        tsparameters.layerDefs = JSON.stringify({
          ['0.0']: `earthquake_id='${eqid}' ` //10022
        })
      }
      if( laycode == "kspgyxcm"){
        tsparameters.layerDefs = JSON.stringify({
          ['0.2']: `earth_quake_id='${eqid}' AND version='${version}'`,
          ['0.1']: `earth_quake_id='${eqid}' AND version='${version}'`,
          ['0.0']: `earth_quake_id='${eqid}'  AND version='${version}'` 
        })
      }
    
      if(laycode == "kspgyxcx"  ){
        tsparameters.layerDefs = JSON.stringify({
          ['0.1']: `earth_quake_id='${eqid}' AND version='${version}'`,
          ['0.0']: `earth_quake_id='${eqid}' AND version='${version}'` 
        })
      }

      if(laycode == "zzj1" || laycode == "zzj0"){
        //  tsparams.LAYERS = "0.1,0.0"
        tsparameters.layerDefs = JSON.stringify({
          ['0.1']: `earthquake_id='${eqid}'`,
          ['0.0']: `earthquake_id='${eqid}'`,
        
        })
      }

    //   if(laycode == "zzj0"){
    //     layers = "0.1,0.0"
    //   }
    //   if(laycode =="zxzzzj"){
    //     layers = "0.1,0.0"
    //   }
    //   if(laycode == "lshpfb" || laycode == "lsczdz" ||laycode == "lsdz" || laycode == "tl" || laycode == "jc" || laycode == "gsl" || laycode == "zhyy" || laycode == "zkyy" || laycode == "yey"  || laycode == "xx" || laycode == "zx" || laycode == "gdyx"){
    //     layers = "0.0,0.1"
    //   }
      var wmsObj = {
        enablePickFeatures: false,
        url: config.SUPERMAPURL + layerUrl,
        layers: layerUrl, // 替换为实际要加载的图层名称  
        id: laycode,
        parameters: memo ? tsparameters : parameters,
        enablePickFeatures:false,
        // 设置矩形范围来限制加载的区域为中国区域
        // tilingScheme: new Cesium.GeographicTilingScheme(),
        crs:"EPSG:4326",
        rectangle: Cesium.Rectangle.fromDegrees(73.48734500000006, 15.701902307507869, 135.08738700000004, 53.561601999099075) // 使用元数据里的地理范围
    }
    if(laycode == "lsdz" || laycode == "lsczdz" || laycode == "zhyy" || laycode == "zkyy" || laycode == "yey" || laycode == "xx" || laycode == "zx" || laycode == "gdyx"){
        wmsObj.getFeatureInfoParameters ={
            query_layers:"0.0,0.1",
            INFO_FORMAT:"application/geojson",
            version:'1.3.0',
            crs:"EPSG:4326"
        }
        wmsObj.enablePickFeatures = true;
    }
    if(laycode == "lshpfb"){
        wmsObj.getFeatureInfoParameters ={
            query_layers:"0.2,0.1,0.0",
            INFO_FORMAT:"application/geojson",
            version:'1.3.0',
            crs:"EPSG:4326",
            FEATURE_COUNT:1
        }
        wmsObj.enablePickFeatures = true;
    }
      
    // WMS图层配置  
    const wmsLayer = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider(wmsObj));

    mimeMap[laycode] = wmsLayer;
    layerFlag[laycode] = true;
}
export const clearLayerFlag = ()=>{
    mimeMap = {};
    layerFlag = {};
}

export function test12() {
    viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
        id: 'setting_seismic_influenceflied',
        url: 'http://10.5.92.115:8090/iserver/services/map-dzyjzhjsptCommon-2/wms130/dzyjzhjspt_proper_guojia',
        layers: '0.0',
        style: '', // 如果WMS服务支持SLD样式，可以在这里指定  
        parameters: {
            transparent: true, // 设置地图背景透明  
            format: 'image/png',
            //    layerDefs: JSON.stringify({
            //     0.0: 'earth_quake_id = 10022'
            //   }),
        },
    }));
}


export const delWmsMap = (id) => {
    if (geojsonData[id]) {
        delEarthQuakeYXC(id)
        return
    }
    if (mimeMap[id]) {
        mimeMap[id].show = false;
        layerFlag[id] = false;
        // viewer.imageryLayers.remove(mimeMap[id]);
        // mimeMap[id] = null;
    }
}


let earthQuakeLonLatView = null;
//根据影响场确定初始范围
export const loadInitView = (id, version)=>{
    var query = {
      tableName: 'setting_seismic_influenceflied',
      fields:
        'uuid,earthquake_level,dz_intensity,long_x,short_y,data_source,remark,earth_quake_id,operate_time,trigger_type,model_id,category,operate_user_id,operate_dept_id,version,type,code,angle,intensity_show,intensity_china_show,area',
      filter: `earth_quake_id='${id}' AND version='${version}' `,
        crs: "4326"
    }
    earthQuakeLonLatView = null;
    onemap.listGeoJsonByTable(query).then((res) => {
      var geojson = JSON.parse(res.geodata.value)
      if(!geojson.features){
        toViewEarthQuakeCenter();
        return
      }  
      geojson.features =  geojson.features.filter(e=>e.properties.dz_intensity > 5)
      const dataSource = new Cesium.GeoJsonDataSource()
      dataSource.load(geojson,{
        stroke: Cesium.Color.GREEN.withAlpha(0),
        fill:  Cesium.Color.RED.withAlpha(0),
      }).then((dataSources) => {
          viewer.dataSources.add(dataSources)
          earthQuakeLonLatView = dataSources.entities.values 
          toViewEarthQuakeCenter()
      })
    })
  }

export function toViewEarthQuakeCenter (){
  if(earthQuakeLonLatView){
    viewer.flyTo(earthQuakeLonLatView,{
        offset: new Cesium.HeadingPitchRange(0, -90, 0),
    })
  }else{
     viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
      store.earthquakeInfo.longitude,
      store.earthquakeInfo.latitude,
      151500
    ),
    duration: 1 // 飞行时间（s）
  })
  }

}

var geojsonData = {};
export const loadEarthQuakeYXC = (id, laycode, version) => {
    var query = {
        tableName: 'setting_seismic_influenceflied',
        fields:
            'uuid,earthquake_level,dz_intensity,long_x,short_y,data_source,remark,earth_quake_id,operate_time,trigger_type,model_id,category,operate_user_id,operate_dept_id,version,type,code,angle,intensity_show,intensity_china_show,area',
        filter: `earth_quake_id='${id}' AND version='${version}' `,
        crs: "4326"
    }
    onemap.listGeoJsonByTable(query).then((res) => {
        let geojson = JSON.parse(res.geodata.value);
        
        if(!geojson.features)return
        geojson.features =  geojson.features.filter(e=>e.properties.dz_intensity > 5)
        const dataSource = new Cesium.GeoJsonDataSource()
        dataSource.load(geojson, {
            stroke: Cesium.Color.fromCssColorString( 'rgba(197, 208, 218, 0.8)') , 
            strokeWidth: 2
        }).then((dataSources) => {
            var index = 10;
            for (const element of dataSources.entities.values) {
                element.polygon.material = Cesium.Color.fromCssColorString( get2dColor(element.properties.dz_intensity._value))
                element.polygon.zIndex = index++;
               // 获取要素的中心位置（这里以多边形为例，简单取其坐标范围的中心，你可根据实际情况调整更精确的获取方式）
                const positions = element.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
                const boundingSphere = Cesium.BoundingSphere.fromPoints(positions);
                const center = boundingSphere.center;
            }

            viewer.dataSources.add(dataSources);
            geojsonData[laycode] = dataSources;
            // 缩放到数据范围
            viewer.zoomTo(dataSources);

        })
    })
}

export const delEarthQuakeYXC = (laycode) => {
    viewer.dataSources.remove(geojsonData[laycode]);
}

export const createPointAndToView = (option) => {
    // 添加一个带有图片的广告牌实体  
    var eobj = {
        _edata: option.data || {},
        zIndex: option.zIndex || 9999,
        type: option.type || "",
        position: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1],option.position[2] || 0), // 经纬度坐标
        billboard: {
            show: option.url ? true : false,
            image: option.url || '/static/icon/poi.png', // 图片的路径  
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 垂直方向的原点  
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 水平方向的原点  
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
        }
    }
    if(option.reference){
       delete eobj.billboard.heightReference 
    }
    if (option.color) {
        eobj.point = {
            show: option.color ? true : false,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
            color: option.color ? Cesium.Color.fromCssColorString(option.color) : Cesium.Color.fromCssColorString('#ff231b'), // 设置点的颜色为绿色（#00FF00）
            pixelSize: option.size ? option.size : 10,
            eyeOffset: new Cesium.Cartesian3(0.0, 0.0, -10.0),
        }
    }
    var billboardEntity = viewer.entities.add(eobj);
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1], option.height || 10000),
        duration: 1, // 飞行时间（s）
    });


    const edit = (option) => {
        billboardEntity.position = Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1],option.position[2] || 0);
        billboardEntity._edata = option.data || {};
        // billboardEntity.type = option.type || "";
        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1], option.height || 10000),
            duration: 1, // 飞行时间（s）
        });

    }
    const del = () => {
        viewer.entities.remove(billboardEntity)
    }

    return { billboardEntity, edit, del };

}

export const createReferencePoint = (option) => {
    var billboardEntity = viewer.entities.add({
        _edata: option.data || {},
        zIndex: 9999,
        type: option.type || "",
        position: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1], 0), // 经纬度坐标（例如：费城）  
        point: {
            show: option.color ? true : false,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
            color: option.color ? Cesium.Color.fromCssColorString(option.color) : Cesium.Color.fromCssColorString('#ff231b'), // 设置点的颜色为绿色（#00FF00）
            pixelSize: option.size ? option.size : 10,
        },

    });
    return billboardEntity
}

export const createPoint = (option) => {
    var obj = {
        _edata: option.data || {},
        zIndex: 9999,
        type: option.type || "",
        position: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1], 0), // 经纬度坐标（例如：费城）  
        billboard: {
            show: option.url ? true : false,
            image: option.url || '/static/icon/poi.png', // 图片的路径  
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
            color: Cesium.Color.fromCssColorString('rgba(255,255,255,1)'), // 使用rgba设置透明度，这里是70%透明的白色，可调整最后一个参数
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER
        },
        point: {
            show: option.color ? true : false,
             heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
            color: option.color ? Cesium.Color.fromCssColorString(option.color) : Cesium.Color.fromCssColorString('#ff231b'), // 设置点的颜色为绿色（#00FF00）
            pixelSize: option.size ? option.size : 10,
        },
        label: {
            text: '起',
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,// 设置贴地
            show: false,
            font: '20px Arial',
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            outlineColor: Cesium.Color.BLACK,
            fillColor: Cesium.Color.WHITE,
            verticalOrigin: Cesium.VerticalOrigin.TOP, // 设置为 TOP，让文本在图标上方
            horizontalOrigin: Cesium.HorizontalOrigin.TOP,
            eyeOffset: new Cesium.Cartesian3(0.0, 0.0, -10.0),
            pixelOffset: new Cesium.Cartesian2(0, -40),
        }
    }

    if(!option.url){
        delete obj.billboard
    }
    if(!option.color){
        delete obj.point
    }

    // 添加一个带有图片的广告牌实体  
    var billboardEntity = viewer.entities.add(obj);
    if (option.label) {
        billboardEntity.label.text = option.label.text;
        billboardEntity.label.show = true;
        if (option.label.color) {
            billboardEntity.label.fillColor = Cesium.Color.fromCssColorString(option.label.color);;
        }
    }

    return billboardEntity
}


export const createPopup = (el, h, c, type) => {
    let handler = null;
    let pickedObject = null;
    let position = null;
    let dom = el || null;
    let dx = 0;
    let dy = 0;
    let hy = h || 65; //额外高度
    let show = false;
    let cb = c || null;
    let s = type || "";

    const handlerMap = () => {
        // 屏幕空间事件处理器  
        handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
        pickedObject = null;
        handler.setInputAction(function (click) {
            if (!s) {
                return
            }
            // 拾取被点击的实体  
            pickedObject = viewer.scene.pick(click.position);

            if (Cesium.defined(pickedObject) && (pickedObject.id.type === s)) {
                // 显示弹出框并设置内容         
                position = pickedObject.id?.position?._value;
                viewer.scene.preRender.removeEventListener(showPopup);
                dom.style.display = 'block';
                setTimeout(() => {
                    dx = dom.clientWidth / 2;
                    dy = dom.clientHeight + hy;
                    showPopup(position);
                }, 0);
                cb && cb(pickedObject.id._edata, pickedObject.id)

                handlerPreRender();
                show = true;
            } else {
                hidePopup();
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    const handlerPreRender = () => {
        viewer.scene.preRender.addEventListener(showPopup)
    }
    function showPopup() {
        // if(dom && dom instanceof HTMLElement)
        var winPosi = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, position)
        if (!winPosi) return
        var x = winPosi.x;
        var y = winPosi.y;
        dom.style.left = x - dx + 'px';
        dom.style.top = y - dy + 'px';

    }

    function hidePopup() {
        if (!show) return
        // handler && handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)//移除事件
        viewer.scene.preRender.removeEventListener(showPopup);
        if (dom) {
            dom.style.display = 'none';
        }
        show = false;
    }

    function closePopup() {
        handler && handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)//移除事件
        viewer.scene.preRender.removeEventListener(showPopup);
        handler = null;
        pickedObject = null;
        position = null;
        dom.style.display = 'none';
        // dom.remove()
        dom = null;
        cb = null;
    }
    function updateH(e) {
        hy = e;
    }
    handlerMap()
    return { closePopup, hidePopup, updateH }
}

export const createPopupNoView = (cb, type) => {
    var s = type
    var handler
    const handlerMap = () => {
        // 屏幕空间事件处理器  
        handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
        handler.setInputAction(function (click) {
            if (!s) {
                return
            }
            // 拾取被点击的实体  
            var pickedObject = viewer.scene.pick(click.position);


            if (Cesium.defined(pickedObject) && (pickedObject.id.type === s)) {
                // 显示弹出框并设置内容         

                cb && cb(pickedObject.id._edata, pickedObject.id)

            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    function closePopup() {
        handler && handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)//移除事件
        handler = null;
    }

    handlerMap()
    return { closePopup }
}


// option:object  position 
export const createPolygon = (option) => {
    var hierarchy = Cesium.Cartesian3.fromDegreesArray([
        -110.0, 25.0,
        -100.0, 25.0,
        -100.0, 35.0,
        -110.0, 35.0
    ]);

    // Create the polygon  
    var polygon = viewer.entities.add({
        name: 'Sample Polygon',
        polygon: {
            hierarchy: hierarchy,
            material: Cesium.Color.RED.withAlpha(0.5)
        }
    });

    // Zoom to the polygon  
    viewer.zoomTo(polygon);

    const edit = (option) => {
        polygon.position = Cesium.Cartesian3.fromDegreesArray([
            -110.0, 25.0,
            -100.0, 25.0,
            -100.0, 35.0,
            -110.0, 35.0
        ]);
    }

    const del = () => {
        viewer.entities.remove(polygon);
        polygon = null;
    }

    return { edit, del }
}

export const createDzRange = (centerLat, centerLon, radii) => {
    // createPoint({position:[105.59777, 40.03883],url:"/static/assets/poi/zh.png",type:"history-point"})
    // 定义圆环的中心点  


    // 定义圆环的材质函数，根据半径调整透明度  
    function createEllipseMaterial(radius, opacity) {
        return new Cesium.ColorMaterialProperty({
            color: new Cesium.Color(1.0, 0.0, 0.0, opacity) // 红色，透明度由 opacity 控制  
        });
    }

    // 创建多层圆环  
    var ellipses = [];
    var radii = [5, 10, 20, 50, 100]; // 不同的半径  
    var opacities = [0.4, 0.3, 0.2, 0.15, 0.1]; // 对应的透明度  

    // radii.forEach((radius, index) => {  
    //     var ellipse = new Cesium.EllipseOutlineGeometry({  
    //         center: center,  
    //         semiMajorAxis: radius,  
    //         semiMinorAxis: radius, // 这里假设是圆形，所以长短半轴相等  
    //         material: createEllipseMaterial(radius, opacities[index])  
    //     });  

    //     var ellipseInstance = new Cesium.GeometryInstance({  
    //         geometry: ellipse  
    //     });  

    //     var primitive = new Cesium.Primitive({  
    //         geometryInstances: ellipseInstance,  
    //         appearance: new Cesium.PerInstanceColorAppearance({  
    //             closed: true  
    //         })  
    //     });  

    //     ellipses.push(primitive);  
    //     viewer.scene.primitives.add(primitive);  
    // });  

    // // 确保视图移动到圆环所在位置  
    // viewer.camera.flyTo({  
    //     destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 1000000.0)  
    // });

    const color = ['#ff3534', '#ff3534', '#ffaf52', '#17fffa', '#a4a5a3'];
    radii.forEach((radius, index) => {
        // 将半径转换为米（Cesium默认使用米作为单位）  
        const radiusInMeters = radius * 1000; // 假设输入半径是以公里为单位  
        var greenCircle = viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 1000),//位置  通过Cesium.Cartesian3.fromDegrees解析经纬高转换为笛卡尔坐标
            zIndex: 999,
            ellipse: { // 椭圆
                semiMinorAxis: radius * 1000, //横向半径
                semiMajorAxis: radius * 1000,//纵向半径
                material: Cesium.Color.RED.withAlpha(0),
                // material: createEllipseMaterial(radius,opacities[index]) ,
                // outlineColor: Cesium.Color.RED || Cesium.Color.fromCssColorString(color[index]), // 可选：设置轮廓颜色 
                // outline: true, // 边框   注意：必须有高度才能设置边框属性,在window下边框width默认1，改变不了
                // outlineWidth: 50, // 设置边框宽度为5（这是可以生效的）
                // zInedx: radii.length - index,
                material: new Cesium.CircleFadeMaterialProperty({
                    color: Cesium.Color.fromCssColorString(color[index]),
                    borderWidthInPx: 10,
                    textureWidth: 512,
                    textureHeight: 512
                }),

            }
        });
        ellipses.push(greenCircle);
    });
    // viewer.camera.flyTo({
    //     destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 500),
    //     duration: 1, // 飞行时间（s）
    // });


    function del() {
        if (ellipses && ellipses.length > 0) {
            for (const item of ellipses) {
                viewer.entities.remove(item)
            }
        }
    }
    return { ellipses, del }
}


//线
export const createLineMark = (option) => {

    const arr = [];
    for (const item of option.position) {
        arr.push(Cesium.Cartesian3.fromDegrees(item[0], item[1], item[2]))
    }
    // 创建线的图形对象
    const polyline = viewer.entities.add({
        _edata: option.data || {},
        zIndex: 99,
        type: option.type || "",
        polyline: {
            positions: arr,
            width: option.width || 2,
            material: option.color ? Cesium.Color.fromCssColorString(option.color) : {}
        },
    });
    // 将视角定位到包含线的区域
    viewer.zoomTo(polyline);
    return polyline
}
//圆形线

export const createCricleLineMark = (option) => {

    var greenCircle = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(option.position[0], option.position[1], option.position[2]),//位置  通过Cesium.Cartesian3.fromDegrees解析经纬高转换为笛卡尔坐标
        _edata: option.data || {},
        zIndex: 99,
        type: option.type || "",
        ellipse: { // 椭圆
            semiMinorAxis: option.radius, //横向半径
            semiMajorAxis: option.radius,//纵向半径
            material: Cesium.Color.RED.withAlpha(0),
            zIndex: 999,
            material: new Cesium.CircleFadeMaterialProperty({
                color: option.color ? Cesium.Color.fromCssColorString(option.color) : "#000",
                borderWidthInPx: option.width,
                textureWidth: 512,
                textureHeight: 512
            }),

        }
    });
    // 将视角定位到包含线的区域
    viewer.zoomTo(greenCircle);
    return greenCircle
}


export const calculateDistanceWithArrays = (point1, point2) => {

    // 提取经纬度值
    var lon1 = point1[0];
    var lat1 = point1[1];
    var lon2 = point2[0];
    var lat2 = point2[1];

    // 将经纬度转换为弧度
    var lon1Rad = Cesium.Math.toRadians(lon1);
    var lat1Rad = Cesium.Math.toRadians(lat1);
    var lon2Rad = Cesium.Math.toRadians(lon2);
    var lat2Rad = Cesium.Math.toRadians(lat2);

    // 使用椭球体模型（这里使用WGS84椭球体）计算距离
    var ellipsoid = Cesium.Ellipsoid.WGS84;
    var pos1 = ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromRadians(lon1Rad, lat1Rad));
    var pos2 = ellipsoid.cartographicToCartesian(Cesium.Cartographic.fromRadians(lon2Rad, lat2Rad));

    return (Cesium.Cartesian3.distance(pos1, pos2) / 1000).toFixed(2);
}







